package vn.bk.hotel;

import java.util.ArrayList;
import java.util.Arrays;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import vn.bk.hotel.adapter.DatabaseHotel;
import vn.bk.hotel.adapter.ImagePagerAdapter;
import vn.bk.hotel.global.Service;
import vn.bk.hotel.object.HotelInfo;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.RatingBar;
import android.widget.TextView;

public class DetailHotel extends BaseActivity {

    public static HotelInfo hotel;

    private TextView addressHotel, textCall;
    private TextView descriptionHotel;
    public static ArrayList<String> imageUrls;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    ViewPager pager;
    boolean isStartDrag = false;

    private DatabaseHotel myDB;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.detail_hotel);
	myDB = new DatabaseHotel(this);
	init();
	setTitle(hotel.getNameHotel());

	// nameHotel.setText(hotel.getNameHotel());
	addressHotel.setText(hotel.getAdress());
	if (hotel.getDescription().trim().length() > 20) {
	    descriptionHotel.setText(hotel.getDescription());
	}
	addMap();

	GetImageUrl getImageUrl = new GetImageUrl(this);
	getImageUrl.execute("run");
    }

    private void addMap() {
	LatLng myLatLng = new LatLng(hotel.getLatitude(), hotel.getLongitude());
	// ratingHotel.setRating(hotel.getNumRate());
	try {
	    MapsInitializer.initialize(this);

	} catch (GooglePlayServicesNotAvailableException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	mMap = ((SupportMapFragment) getSupportFragmentManager()
		.findFragmentById(R.id.map)).getMap();

	mMap.addMarker(new MarkerOptions().position(myLatLng)
		.icon(BitmapDescriptorFactory
			.fromResource(R.drawable.map_pin_normal)));

	mMap.getUiSettings().setZoomControlsEnabled(false);
	mMap.animateCamera(CameraUpdateFactory
		.newCameraPosition(new CameraPosition(myLatLng, 15, 0, 0)));

	mMap.setOnMapClickListener(new OnMapClickListener() {

	    @Override
	    public void onMapClick(LatLng arg0) {
		ViewMap.myHotel = hotel;
		startActivity(new Intent(DetailHotel.this, ViewMap.class));
	    }
	});
    }

    private void setPagerView() {
	Log.i("TAG", "Set pager view");
	pager.setAdapter(new ImagePagerAdapter(DetailHotel.this, imageUrls,
		imageLoader, options));
	pager.setCurrentItem(0);
    }

    private void init() {

	pager = (ViewPager) findViewById(R.id.pager);
	addressHotel = (TextView) findViewById(R.id.tv_address);
	descriptionHotel = (TextView) findViewById(R.id.tv_description);

	imageLoader = ImageLoader.getInstance();
	imageLoader.init(ImageLoaderConfiguration.createDefault(this));

	options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.ic_empty)
		.showImageOnFail(R.drawable.ic_empty).cacheInMemory()
		.cacheOnDisc().displayer(new RoundedBitmapDisplayer(0)).build();
	textCall = (TextView) findViewById(R.id.tv_call);
	if (hotel.getPhone().equals("anyType{}") || hotel.getPhone() == null
		|| hotel.getPhone().equals("")) {
	    textCall.setVisibility(TextView.INVISIBLE);
	} else {
	    textCall.setText(hotel.getPhone());
	}
	Linkify.addLinks(textCall, Linkify.ALL);

	((RatingBar) findViewById(R.id.ratingbar_hotel)).setRating(hotel
		.getNumRate());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	MenuInflater inflater = getSupportMenuInflater();
	inflater.inflate(R.menu.detail_bar, menu);
	final MenuItem favoriteItem = menu.findItem(R.id.add_favorite_bar);

	if (myDB.isExistInDatabase(hotel)) {
	    favoriteItem.setIcon(R.drawable.bt_favor);
	} else {
	    favoriteItem.setIcon(R.drawable.add_favorite);
	}

	favoriteItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {

	    @Override
	    public boolean onMenuItemClick(MenuItem item) {
		// TODO Auto-generated method stub
		if (myDB.isExistInDatabase(hotel)) {
		    favoriteItem.setIcon(R.drawable.add_favorite);
		    myDB.deleteHotel(hotel);
		} else {
		    favoriteItem.setIcon(R.drawable.bt_favor);
		    myDB.createHotel(hotel);
		}

		return false;
	    }
	});
	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	// if (item.getItemId() == android.R.id.home) {
	// finish();
	// }
	return super.onOptionsItemSelected(item);
    }

    public class GetImageUrl extends AsyncTask<String, Integer, String> {

	private Context mContext;
	private boolean isFind = true;
	private String[] arrayImage;

	public GetImageUrl(Context context) {
	    this.mContext = context;
	    // progressLoad.setVisibility(ProgressBar.VISIBLE);
	    // ga.setVisibility(Gallery.INVISIBLE);
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();

	}

	@Override
	protected String doInBackground(String... params) {

	    try {
		arrayImage = Service.getHotelService().getAllImageOfPlace(
			hotel.getUri());

	    } catch (Exception e) {
		isFind = false;
	    }
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);

	    // progressLoad.setVisibility(ProgressBar.INVISIBLE);
	    // ga.setVisibility(Gallery.VISIBLE);
	    Log.i("on post", "post complelte");
	    if (isFind) {
		Log.i("size list image start",
			String.valueOf(arrayImage.length));
		imageUrls = new ArrayList<String>(Arrays.asList(arrayImage));
		if (imageUrls.size() == 1) {
		    String oneData = imageUrls.get(0);
		    imageUrls.add(oneData);
		    imageUrls.add(oneData);
		    imageUrls.add(oneData);
		}
		Log.i("size list image end", String.valueOf(imageUrls.size()));
		// ga.setAdapter(new ImageAdapter(mContext));
		setPagerView();
	    }

	}

    }

}
